package com.allwees.bs.module.oms.event.listener;

import com.allwees.bs.module.oms.dao.OrderDao;
import com.allwees.bs.module.oms.dao.OrderItemDao;
import com.allwees.bs.module.oms.dao.OrderSkuSnapDao;
import com.allwees.bs.module.oms.entity.Order;
import com.allwees.bs.module.oms.entity.OrderItem;
import com.allwees.bs.module.oms.entity.OrderSkuSnap;
import com.allwees.bs.module.oms.event.OrderRefundSuccessEvent;
import com.allwees.bs.module.ums.service.DeviceService;
import com.allwees.sender.AppSender;
import com.allwees.sender.MessageSender;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class OrderRefundSuccessListener {

    private final static String LINK = "AccountOrderDetailPage";
    private final static String NOTIFY_TITLE = "Refund successful";
    private final static String NOTIFY_CONTENT = "Thank you for shopping with us. Your order has been refunded.";

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private OrderSkuSnapDao orderSkuSnapDao;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private MessageSender messageSender;

    @Async
    @EventListener
    @Transactional
    public void on(OrderRefundSuccessEvent event) {
        String orderItemUuid = (String) event.getSource();

        OrderItem orderItem = orderItemDao.findByUuid(orderItemUuid);
        if (orderItem == null) {
            return;
        }

        Order order = orderDao.findByUuid(orderItem.getOrderUuid());
        if (order == null) {
            return;
        }

        String jpushId = deviceService.getPushId(order.getUserUuid());
        send(jpushId, order.getUserUuid(), order.getUuid(), getMainPhoto(orderItem.getOrderUuid(), orderItem.getSkuUuid()));
    }

    private void send(String jpushId, String userUuid, String orderUuid,String mainPhoto) {
        if (StringUtils.isNotBlank(jpushId)) {
            AppSender.push(jpushId, NOTIFY_TITLE, NOTIFY_CONTENT);
        }
        Map<String, String> params = new HashMap<>();
        params.put("orderUuid", orderUuid);
        messageSender.send(userUuid, NOTIFY_TITLE, NOTIFY_CONTENT, LINK, mainPhoto, params);
    }

    private String getMainPhoto(String orderUuid,String skuUuid) {
        OrderSkuSnap orderSkuSnap = orderSkuSnapDao.findOne(orderUuid, skuUuid);
        return orderSkuSnap != null ? orderSkuSnap.getProductPhoto() : "";
    }
}
